package com.itheima.controller.v1;

import com.itheima.common.MsgResult;
import com.itheima.common.R;
import com.itheima.controller.v1.api.UserControllerApi;
import com.itheima.dto.LoginDto;
import com.itheima.pojo.SysUser;
import com.itheima.service.SysUserService;
import com.itheima.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin
public class UserController implements UserControllerApi {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;

    //用户登录
    @Override
    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto) {
        //获取生成的验证码
        String code = (String) redisTemplate.opsForValue().get(loginDto.getUuid());
        log.info("验证码=="+code);
        //判断登录状态
        R r =sysUserService.login(loginDto,code);
        if (r.getCode()==1){ //登陆成功
            SysUser user = (SysUser) r.getData();
            String jwt = JwtUtil.createJWT(user.getUserId().toString(), user.getUserName(), 60 * 24 * 1000 * 5L);
            redisTemplate.opsForValue().set("username",user.getUserName());
            return new R(1,MsgResult.SUCCESS_LOGIN,jwt);
        }
        return r;
    }

    //用户注销
    @Override
    @GetMapping("/logout")
    public R logout(){
        HttpSession session = request.getSession();
        session.invalidate();
        log.info("退出成功");
        return new R(1,MsgResult.SUCCESS_LOGOUT,null);
    }
}
